﻿using System;
using System.Data;
using System.Linq;
using System.ServiceModel;
using KPIS.GERP.Models;
using KPIS.GERP.Models.SYS;
using KPIS.GERP.Models.ViewModel;

namespace KPIS.GERP.WCF.GHRMS
{
    public static class ServerVariables
    {
        static ServerVariables()
        {
            InitialStartLog = new VMInitialStartLog();
        }

        public static VMInitialStartLog InitialStartLog { get; set; }
    }

    [ServiceContract]
    public interface IGhrmsWakeUpService
    {
        [OperationContract]
        void WakeUp();
        [OperationContract]
        VMInitialStartLog GetInitialTime();
    }
    public class GhrmsWakeUpService : IGhrmsWakeUpService
    {
        public void WakeUp()
        {
            ServerVariables.InitialStartLog.Start();

            DateTime firstSelectDbStartDateTime = DateTime.Now;
            TimeSpan firstSelectDb, firstSaveDb;
            MockQuerySelect();
            firstSelectDb = DateTime.Now.Subtract(firstSelectDbStartDateTime);

            DateTime firstSaveDbStartDateTime = DateTime.Now;
            var m = MockQuerySave();
            firstSaveDb = DateTime.Now.Subtract(firstSaveDbStartDateTime);

            m.Description = "First database select time used = " + firstSelectDb.TotalSeconds.ToString("#,##0") + " seconds , save time used = " + firstSaveDb.TotalSeconds.ToString("#,##0") + " seconds. Remarks: this message is generated by System";

            MockQueryUpdate(m);
            ServerVariables.InitialStartLog.FinishedInitial();

        }

        public VMInitialStartLog GetInitialTime()
        {
            return ServerVariables.InitialStartLog;
        }

        private void MockQueryUpdate(ServerStartUp newMessage)
        {
            using (var db = new GERPContext(false))
            {
                db.Entry(newMessage).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();
            }
        }

        private ServerStartUp MockQuerySave()
        {
            using (var db = new GERPContext(false))
            {
                var newMessage = new ServerStartUp()
                {
                    System = "WCF.GIMS",
                    DateInit = DateTime.Now,
                    Title = "Server service GIMS has been invoke and test call database",
                     
                };

                db.ServerStartUps.Add(newMessage);
                db.SaveChanges();
                return newMessage;
            }
        }

        private void MockQuerySelect()
        {
            using (var db = new GERPContext(false))
            {
                var sysMessage = db.ServerStartUps.ToList();
            }
        }
    }
}
